const express = require('express');
const opn = require('opn');
const WebSocketServer = require('./scripts/websocket-server');

const app = express();
const port = 9999;

app.use(express.static(__dirname));

app.get('/', (req, res) => {
    res.sendFile(__dirname + '/index.html');
})

const ws = new WebSocketServer({port: 8888});

ws.defineUtil((connCaches) => {
    return {
        getAllUser() {
            return Object.values(connCaches).map(connObj => connObj.user);
        }
    }
})

ws.onconnection((socket, utils) => {
    // 登录事件
    socket.$on('login', (data) => {

        if (utils.checkLogin(data.user)) {
            socket.$emit('login result', {
                success: false,
                message: '用户名已存在，请更换'
            });
        } else {
            utils.login(socket, data.user, () => {
                socket.$emit('login result', {
                    success: true,
                    message: '登陆成功',
                    historyMessage: utils.getHistoryMessage(),
                });
                ws.$broadcast('online update', {
                    onlineUsers: utils.getAllUser()
                })
            })
        }
    });
    // 聊天事件
    socket.$on('message', (data) => {
        ws.$broadcast('new message', data);
    });
    // 注销事件
    ws.ondisconection((data) => {
        ws.$broadcast('user leave', {
            user: data.user
        });
        ws.$broadcast('online update', {
            onlineUsers: utils.getAllUser()
        });
    });
});

app.listen(port, () => {
    console.log('server run in '+ port +' port...');
    opn('http://localhost:' + port);
});
